<?php
namespace app\manage\controller;
use think\Db;
use app\model\Order;
use app\model\Channel;
use app\model\Withdrawal;
use app\model\Mch;
use think\Controller;

class Base extends Controller
{
   /**
    * Undocumented 菜单组装
    *
    * @param [type] $cate
    * @param string $lefthtml
    * @param integer $pid
    * @param integer $lvl
    * @param integer $leftpin
    * @return void
    */
    public function getMenu($cate , $lefthtml = '└─' , $pid=0 , $lvl=0, $leftpin=0){
		$arr=array();
		foreach ($cate as $v){
			if($v['pid']==$pid){
				$v['leftpin']=$leftpin + 0;//左边距
				$v['lefthtml']=str_repeat($lefthtml,$lvl);
				$arr[]=$v;
				$arr= array_merge($arr,self::getMenu($cate,$lefthtml,$v['id'],$lvl+1 , $leftpin+20));
			}
		}
		return $arr;
    }
    /**
     * Undocumented 订单统计
     *
     * @param [type] $data
     * @return void
     */
    public function orderTotal($data){
        $list = Order::alias('a')->where(function($query) use($data){

        })->join('channel b','a.channel_id = b.id')->select();
    }
    /**
     * Undocumented 订单导出
     *
     * @param [type] $data
     * @return void
     */
    public function order_export($data){
        $list = Order::alias('a')->where(function($query) use($data){
            //订单状态
            if(!empty($data['pay_status'])){
                $query->where("a.pay_status",$data['pay_status']);
            }
            //通知状态
            if(!empty($data['notice'])){
                $query->where("a.notice",$data['notice']);
            }
            //渠道id
            if(!empty($data['channel'])){
                $query->where("a.channel_id",$data['channel']);
            }
            //支付类型id
            if(!empty($data['payment'])){
                $query->where("a.pay_code",$data['payment']);
            }
            //最小金额
            if(!empty($data['min_amount']) && !empty($data['max_amount'])){
                $query->where("a.amount",'>=',$data['min_amount'])->whereOr("amount",'<=',$data['max_amount']);
            }
            //商户单号/系统单号
            if(!empty($data['keyword'])){
                $query->where("a.out_trade_no|a.systen_no",'like','%'.$data['keyword'].'%');
            }
            //商户号/商户名称
            if(!empty(trim($data['mch']))){
                $mch = Mch::where("a.mch|a.mch_name",'like','%'.trim($data['mch']).'%')->column("mch");
                if(!empty($mch)){
                    $query->where("a.mch_id",'in',$mch);
                }
            }
            //时间区间
            if(!empty($data['start']) && !empty($data['end'])){
                $query->where("a.create_time","between",[$data['start'],$data['end']]);
            }
        })
        ->join('channel b','a.channel_id = b.id')
        ->field("
            a.id,
            a.mch_id,
            a.out_trade_no,
            a.systen_no,
            b.title as channel,
            a.pay_code as payment,
            a.run_rate,
            a.amount,
            a.actual_amount,
            a.total_fee,
            a.settle,
            case a.pay_status when 1 then '未支付' when 2 then '已支付' else '已关闭' end ,
            IF(a.notice=1,'未通知','已通知') AS notice,
            a.agent_rate,
            a.agent_amount,
            a.cost_rate,
            a.upstream_settle,
            a.Platform,
            a.create_time,
            a.pay_time,
            a.remark
        ")
        ->select()->toArray();
        if(count($list) >= 50000){
            exit("最大一次导出5万条数据<a style='padding: 3px 10px;border: 1px solid #009f95;background: #009f95;color: white;text-decoration: none;border-radius: 3px;margin-left: 10px;' href='/manage/order'>返回</a>");
        }
        $title = [
            "ID",
            "商户号",
            "订单号",
            "系统单号",
            "渠道",
            "支付类型",
            "运营费率",
            "下单金额",
            "实际支付",
            "手续费",
            "结算金额",
            "支付状态",
            "通知状态",
            "代理费率",
            "代理收益",
            "成本费率",
            "上游结算",
            "平台收益",
            "下单时间",
            "支付时间",
            "备注"
        ];
        $this->export($list,'订单', $title);
    }
    /**
     * Undocumented 商户收益明细导出
     *
     * @param [type] $data
     * @return void
     */
    public function mch_record_export($data){
        $list = Db::name("mch_record")->alias('a')->order("a.id",'desc')->where(function($query) use($data){
            
            //商户号/商户名称
            if(!empty($data['keyword'])){
                $query->where("b.mch",'like','%'.$data['keyword'].'%')->whereOr("b.mch_name",'like','%'.$data['keyword'].'%');
            }
            //类型
            if(!empty($data['type'])){
                $query->where("a.type",$data['type']);
            }
            //订单号
            if(!empty($data['order'])){
                $query->where("a.order_sn",'%'.$data['order'].'%');
            }
            //创建时间区间
            if(!empty($data['start']) && !empty($data['end'])){
                $query->where("a.create_time",'between',[$data['start'],$data['end']]);
            }
        })->join("mm_mch b",'a.mch_id = b.mch')
        ->field("
        a.mch_id,
        a.order_sn,
        a.balance,
        a.total_balance,
        case a.type 
        when 1 then '手动增加' 
        when 2 then '手动减少' 
        when 3 then '手动冻结' 
        when 4 then '手动解除' 
        when 5 then '商户支付' 
        when 6 then '强制入账' 
        when 7 then '商户提现' 
        else '提现失败' end ,
        a.remark,
        a.create_time
        ")->select();
        $title = [
            "商户号","订单号","变更金额","变更后余额","类型","备注","创建时间"
        ];
        $this->export($list,'商户收益明细', $title);
    }
    /**
     * Undocumented 出款导出
     *
     * @return void
     */
    public function with_export($data){

        $list = Withdrawal::alias('a')->order('a.id','desc')->where(function($query) use($data){
            //出款状态
            if(!empty($data['status'])){
                $query->where("a.status",$data['status']);
            }
            //商户号
            if(!empty($data['status'])){
                $query->where("a.mch_id",'like','%'.$data['status'].'%');
            }
            //时间区间
            if(!empty($data['start']) && !empty($data['end'])){
                $query->where("a.create_time",'between',[$data['start'],$data['end']]);
            }
        })
        ->field("
            a.id,
            IF(a.type=1,'商户','代理') AS type,
            a.mch_id,
            a.poundage,
            a.total_fee,
            a.actual_fee,
            b.account_name,
            b.card_number,
            b.bank_name,
            b.branch,
            b.location,
            case a.status when 1 then '未处理' when 2 then '处理中' when 3 then '已打款' else '已退款' end ,
            a.create_time,
            a.update_time,
            a.channel,
            a.lock_name,
            a.remark
        ")->join("bank_card b",'a.bank_id = b.id')->select()->toArray();
        if(count($list) >= 50000){
            exit("最大一次导出5万条数据<a style='padding: 3px 10px;border: 1px solid #009f95;background: #009f95;color: white;text-decoration: none;border-radius: 3px;margin-left: 10px;' href='/manage/with'>返回</a>");
        }
        $title = [
            "ID",
            "角色",
            "商户号",
            "手续费",
            "申请金额",
            "实际到账",
            "开户人",
            "银行卡号",
            "所属银行",
            "所在支行",
            "开卡城市",
            "申请状态",
            "申请时间",
            "处理时间",
            "出款渠道",
            "处理人",
            "备注"
        ];
        $this->export($list,'出款', $title);
    }
    /**
     * Undocumented 渠道统计导出
     *
     * @return void
     */
    public function chan_export($data){
        $list = Db::name("chan_statistical")->alias('a')->where(function($query) use($data){
            //渠道
            if(!empty($data['channel'])){
                $query->where('a.channel_id',$data['channel']);
            }
            //时间
            if(!empty($data['start'])){
                $query->where('a.create_time',$data['start']);
            }
        })
        ->join('channel b','a.channel_id = b.id')
        ->field("
            b.title,
            a.pay_code as payment,
            a.create_time,
            a.amount,
            a.max_count,
            a.actual_amount,
            a.succ_num,
            a.err_pay_amount,
            a.error_num,
            a.settle,
            a.agent_amount,
            a.upstream_settle,
            a.platform
        ")->select();
        $title = [
            "渠道名称",
            "支付类型",
            "日期",
            "总请求数",
            "总笔数",
            "支付成功",
            "成功笔数",
            "未支付",
            "未支付笔数",
            "商户结算金额",
            "代理结算金额",
            "上游结算金额",
            "平台盈利"
        ];
        $this->export($list,'渠道统计', $title);
    }
    /**
     * Undocumented 商户统计导出
     *
     * @return void
     */
    public function mch_export($data){
        $list = Db::name("mch_statistical")->where(function($query) use($data){
           
            if(!empty($data['keyword'])){
                $mch = Mch::where('mch|mch_name','like','%'.$data['keyword'].'%')->column('mch');
                if(!empty($mch)){
                    $query->where('mch_id','in',$mch);
                }
            }
            if(!empty($data['start'])){
                $query->where('create_time',$data['start']);
            }
        })
        ->field("
            mch_id,
            create_time,
            max_amount,
            max_count,
            actual_amount,
            succ_num,
            pay_amount,
            err_num,
            settle,
            total_fee
        ")->select();
        $title = [
            "商户号",
            "日期",
            "请求总额",
            "请求笔数",
            "实际支付金额",
            "支付笔数",
            "未支付金额",
            "未支付笔数",
            "商户结算金额",
            "商户手续费"
        ];
        $this->export($list,'商户统计', $title);
    }
    /**
     * Undocumented 平台收益统计导出
     *
     * @return void
     */
    public function platform_export($data){
        $list = Db::name("platformh_statistical")->where(function($query) use($data){
            if(!empty($data['start'])){
                $query->where('create_time',$data['start']);
            }
        })->field("
            create_time,
            max_amount,
            max_count,
            actual_amount,
            succ_num,
            err_amount,
            err_num,
            settle,
            agent_amount,
            upstream_settle,
            platform
        ")->select();
        $title = [
            "日期",
            "总请求金额",
            "笔数",
            "已支付",
            "笔数",
            "未支付",
            "笔数",
            "商户结算",
            "代理结算",
            "上游结算",
            "平台盈利"
        ];
        $this->export($list,'平台统计', $title);
    }
    /**
     * Undocumented 平台统计导出
     *
     * @param [type] $list 数组
     * @param [type] $name  表名
     * @param [type] $title 表头
     * @return void
     */
    private function export($list,$name, $title){
        ini_set('max_execution_time', 100);// 设置PHP超时时间
        ini_set('memory_limit', '500M');// 设置PHP临时允许内存大小
         //路径
         $fileName = $name. date('Ymd_His') . '.csv';
         $filePath = '../' . $fileName;
         $index = 0;
         $fp = fopen($filePath, 'w'); //生成临时文件
         chmod($filePath, 0777);//修改可执行权限
        fputcsv($fp, $title);
        foreach ($list as  &$item) {
            if(!empty($item['payment'])){
                $item['payment'] = Channel::paymentType($item['payment']);
            }
            foreach ($item as $k => $v) {
                $item[$k] = $v . "\t";
                //每次写入1000条数据清除内存
                if ($index == 10000) { 
                    $index = 0;
                    ob_flush();//清除内存
                    flush();
                }
                $index++;
            }
            fputcsv($fp, $item);
        }
        ob_flush();
        fclose($fp);  //关闭句柄
        header("Cache-Control: max-age=0");
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($fileName));
        header("Content-Type: text/csv");
        header("Content-Transfer-Encoding: binary");
        header('Content-Length: ' . filesize($filePath));
        @readfile($filePath);//输出文件;
        unlink($filePath); //删除压缩包临时文件
    }

}